<template>
  <el-table
    v-loading="isLoading"
    :data="shops"
    :tree-props="tableTreeProps"
    border
    default-expand-all
    row-key="selfid"
  >
    <el-table-column label="门店名称" prop="shop_name" />
    <el-table-column label="负责人" prop="manager.username" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button
          v-if="row.level < 3"
          link
          type="primary"
          @click="handleAddClick(row.selfid, row.shop_name)"
        >
          新增下级
        </el-button>
        <el-button
          v-if="row.selfid !== 0"
          link
          type="primary"
          @click="handleEditClick(row)"
          >修改</el-button
        >
        <!-- <el-popconfirm v-if="row.selfid !== 0" title="是否确定删除？" @confirm="handleDeleteConfirm(row.selfid)">
          <template #reference>
            <el-button link type="danger">删除</el-button>
          </template>
        </el-popconfirm> -->
      </template>
    </el-table-column>
  </el-table>
  <shop-dialog
    v-model="shopToAdd"
    v-model:show="isAddDialogShow"
    :parent-name="shopToAddParentName"
    @success="handleDialogSuccess"
  />
  <shop-dialog
    v-model="shopToEdit"
    v-model:show="isEditDialogShow"
    :init-manager="shopToEditInitManager"
    @success="handleDialogSuccess"
  />
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { deleteShopBySelfId, getShops } from "@/api/shop";
import { ProcessedShopResponse, ShopRequest, ShopResponse } from "@/api/types/shop";
import ShopDialog from "@/components/dialog/ShopDialog.vue";
import { isAxiosError } from "axios";

const shops = ref<ProcessedShopResponse[]>([]);
const isLoading = ref(false);
const isAddDialogShow = ref(false);
const isEditDialogShow = ref(false);
const shopToAdd = ref<ShopRequest>();
const shopToAddParentName = ref<string>();
const shopToEdit = ref<ShopRequest>();
const shopToEditInitManager = ref<{ departmentId: number; userId: string }>();
const tableTreeProps = {
  children: "childs",
};

async function getData() {
  if (isLoading.value == false) {
    isLoading.value = true;
  }
  const { result } = await getShops();
  if (result !== undefined) {
    shops.value = [
      {
        level: 1,
        shop_name: import.meta.env.VITE_SHOP_NAME,
        childs: result.map((shopResponse) => ({
          ...shopResponse,
          level: 2,
          childs: shopResponse.childs?.map(
            (shopResponse) =>
              ({
                ...shopResponse,
                level: 3,
              } as ProcessedShopResponse)
          ),
        })),
        selfid: 0,
      } as ProcessedShopResponse,
    ];
    isLoading.value = false;
  }
}

getData();

function handleAddClick(selfId: number, shopName: string) {
  shopToAdd.value = { pid: selfId };
  shopToAddParentName.value = shopName;
  isAddDialogShow.value = true;
}

async function handleDeleteConfirm(selfId: number) {
  try {
    const { code, msg } = await deleteShopBySelfId(selfId);
    if (code == "200") {
      ElMessage.success(msg);
      await getData();
    } else {
      ElMessage.error(msg);
    }
  } catch (error) {
    if (isAxiosError(error) && error.response?.data.message != undefined) {
      ElMessage.error(error.response?.data.message);
    }
  }
}

function handleEditClick(shopResponse: ShopResponse) {
  shopToEdit.value = {
    id: shopResponse.id,
    selfid: shopResponse.selfid,
    pid: shopResponse.pid,
    shop_name: shopResponse.shop_name,
    manager: shopResponse.manager?.userid,
    address: shopResponse.address,
    latitude:
      shopResponse.latitude !== undefined ? Number(shopResponse.latitude) : undefined,
    longitude:
      shopResponse.longitude !== undefined ? Number(shopResponse.longitude) : undefined,
    isarea: shopResponse.isarea,
    is_new: shopResponse.is_new,
    is_island: shopResponse.is_island,
    // award_gangdao:shopResponse.award_gangdao,
    plan_users: shopResponse.plan_users,
    center_code: shopResponse.center_code,
    isHandleEdit: true,
  };

  // console.log(shopResponse.isarea);

  if (
    shopResponse.manager?.dept_id !== undefined &&
    shopResponse.manager.userid !== undefined
  ) {
    if (
      shopResponse.manager.dept_id === "不存在的部门" ||
      shopResponse.manager.userid === "不存在的用户"
    ) {
      shopToEditInitManager.value = undefined;
    } else {
      shopToEditInitManager.value = {
        departmentId: shopResponse.manager?.dept_id as number,
        userId: shopResponse.manager?.userid,
      };
    }
  }
  isEditDialogShow.value = true;
}

async function handleDialogSuccess() {
  await getData();
}
</script>
